package com.wujunshen.chess.engine;

import com.github.bhlangonijr.chesslib.Board;
import com.github.bhlangonijr.chesslib.move.Move;
import com.wujunshen.chess.StartPosition;
import java.util.List;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;

/**
 * @author wujunshen
 */
@NoArgsConstructor
public class TreeEngine {
  public void buildTree(@NotNull Node node, int layer, int depth) {
    if (node.getResult() != null) {
      return;
    }

    // 如果层级数字超过给定的深度，则后续层级中的子节点不需要在树中构建
    if (layer >= depth) {
      return;
    }

    List<Node> childrenNodes = node.getChildrenNodes();
    for (Move legalMove : node.getBoard().legalMoves()) {
      Board childBoard = node.getBoard().clone();
      childBoard.doMove(legalMove);

      StartPosition childPosition = new StartPosition();
      childPosition.setBoard(childBoard);

      Node childNode = new Node(childPosition);
      childNode.evaluate();

      childrenNodes.add(childNode);
    }

    if (!childrenNodes.isEmpty()) {
      // 如果 layer 是偶数，且 node 的 board 的 getSideToMove 等于 StartPosition 的 initSide
      // 则按照 childrenNodes 的node value 最大到最小排列
      // 反之,按照 childrenNodes 的node value 最小到最大排列
      childrenNodes =
          childrenNodes.stream()
              .sorted((i1, i2) -> Float.compare(i1.getValue(), i2.getValue()))
              .toList();
      if (layer % 2 == 0 && node.getBoard().getSideToMove() == StartPosition.initSide) {
        childrenNodes = childrenNodes.reversed();
      }

      layer++;
      for (Node childNode : childrenNodes) {
        buildTree(childNode, layer, depth);
      }
    }
    node.setChildrenNodes(childrenNodes);
  }
}
